package com.websocket.service.dispatch;

import com.websocket.MessageData;
import com.websocket.WebSocketConfig;
import com.websocket.converter.MessageConverter;
import com.websocket.service.mapping.HandlerExecution;
import com.websocket.service.adapter.WebSocketHandlerAdapter;
import com.websocket.service.mapping.WebSocketHandlerMapping;
import com.websocket.service.WebSocketTemplate;
import org.java_websocket.WebSocket;
import org.springframework.context.ApplicationContext;

import java.security.Principal;

public class WebSocketDispatch {

    private final WebSocketConfig webSocketConfig;

    private WebSocketHandlerMapping handlerMapping;
    private WebSocketHandlerAdapter handlerAdapter;

    public WebSocketDispatch(WebSocketConfig config, ApplicationContext context, WebSocketTemplate template) {
        webSocketConfig = config;
        initHandlerMapping(config, context);
        initHandlerAdaptor(config, template);
    }

    public void doDispatch(WebSocket conn, String message, Principal user) {
        MessageConverter converter = webSocketConfig.converter;
        MessageData messageData = converter.parse(message, MessageData.class);

        // 获取handler执行器
        HandlerExecution handler = handlerMapping.getHandler(messageData);

        // 处理handler执行器
        handlerAdapter.handle(handler, messageData, conn, user);
    }

    private void initHandlerMapping(WebSocketConfig config, ApplicationContext context) {
        handlerMapping = new WebSocketHandlerMapping(context, config.interceptorRegistry);
    }

    private void initHandlerAdaptor(WebSocketConfig config, WebSocketTemplate template) {
        handlerAdapter = new WebSocketHandlerAdapter(config, template);
    }
}
